import { NextRequest, NextResponse } from "next/server";
import db from "@/db/db";
export async function GET(request: NextRequest) {
  const { posts } = db.data;
  const searchParams = request.nextUrl.searchParams;
  const query = searchParams.get("query")||'';
  const pageNum = searchParams.get("pageNum") || "1";
  const pageSize = searchParams.get("pageSize") || "2";
  const post = query ? posts.filter(post => post.title.includes(query) || post.content.includes(query)) : posts;
  const startIndex = (parseInt(pageNum) - 1) * parseInt(pageSize);
  const endIndex = startIndex + parseInt(pageSize);
  const paginatedPosts = post.slice(startIndex, endIndex);
  return NextResponse.json({
    code: '0',
    msg: "Posts fetched",
    pageNum: parseInt(pageNum),
    totalPages: Math.ceil(post.length / parseInt(pageSize)),
    total: post.length,
    data: paginatedPosts
  });
  
}

export async function POST(request: Request) {
  const body = await request.json();
  await db.update(({posts}) => {
    posts.unshift({
      id: Math.random().toString(36).substring(2, 9),
      ...body
    })
  });
  return NextResponse.json({ message: "Post received" });
}